package com.mengxuegu.springboot.config;

import com.alibaba.fastjson.JSON;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * List<String> 的类型转换器实现类，对应数据库的 varchar 类型
 *
 * @author 永不言败
 * @since 2022 3/23 12:50:15
 */
@MappedJdbcTypes(JdbcType.VARCHAR)
@MappedTypes(List.class)
public class StringListTypeHandler extends BaseTypeHandler<List<String>> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<String> strings, JdbcType jdbcType) throws SQLException {
        ps.setString(i, JSON.toJSONString(strings));
    }

    @Override
    public List<String> getNullableResult(ResultSet rs, String s) throws SQLException {
        String jsonString = rs.getString(s);
        return JSON.parseArray(jsonString, String.class);
    }

    @Override
    public List<String> getNullableResult(ResultSet resultSet, int i) throws SQLException {
        return null;
    }

    @Override
    public List<String> getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return null;
    }
}
